package com.carpedil.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.carpedil.common.dto.UserDTO;

import java.util.Date;
import java.util.HashMap;

/** @author Administrator */
public class JwtUtil {
  private static final long EXPIRE_TIME = 1000 * 60 * 5;
  private static final String TOKEN_SECRET = "J78";

  public static String createToken(UserDTO userDto) {
    // 过期时间
    Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
    // 私钥及加密算法
    Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
    // 设置头信息
    HashMap<String, Object> header = new HashMap<>(2);
    header.put("typ", "JWT");
    header.put("alg", "HS256");
    // 附带username和userID生成签名
    return JWT.create()
        .withHeader(header)
        .withClaim("username", userDto.getUsername())
        .withClaim("perm", userDto.getPerm())
        .withExpiresAt(date)
        .sign(algorithm);
  }

  /**
   * 认证
   *
   * @param token token
   * @return UserDto
   */
  public static UserDTO verifierJwt(String token) {
    // 私钥及加密算法
    Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
    UserDTO userDto = null;
    JWTVerifier verifier = JWT.require(algorithm).build();
    try {
      DecodedJWT jwt = verifier.verify(token);
      userDto = new UserDTO();
      // 从token中取出内容
      userDto.setPerm(jwt.getClaim("perm").asInt());
      userDto.setUsername(jwt.getClaim("username").asString());
    } catch (Exception e) {
      return userDto;
    }
    return userDto;
  }
}
